package com.ckd.flyingtrip.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.fragment.HomeFragment;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
//import com.googlecode.tesseract.android.TessBaseAPI;
import com.huawei.hms.mlplugin.card.icr.cn.MLCnIcrCapture;
import com.huawei.hms.mlplugin.card.icr.cn.MLCnIcrCaptureConfig;
import com.huawei.hms.mlplugin.card.icr.cn.MLCnIcrCaptureFactory;
import com.huawei.hms.mlplugin.card.icr.cn.MLCnIcrCaptureResult;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 实名认证---飞哥出行
 * 9-24
 */
public class NameRenzhengActivity extends BaseActivity {
    @BindView(R.id.toolber_color_title)
    TextView title;
    @BindView(R.id.btn_one)
    ImageView btnOne;
    @BindView(R.id.btn_two)
    ImageView btnTwo;
    @BindView(R.id.name_renzheng_namell)
    LinearLayout namell;
    @BindView(R.id.edit_name)
    TextView editName;
    @BindView(R.id.name_renzheng_sfzhll)
    LinearLayout sfzhll;
    @BindView(R.id.edit_sfzh)
    TextView editSfzh;
    @BindView(R.id.btn_res)
    Button btnRes;
    @BindView(R.id.name_renzheng_cityll)
    LinearLayout cityll;
    @BindView(R.id.eidt_city)
    TextView eidtCity;
    @BindView(R.id.name_renzheng_sexll)
    LinearLayout sexll;
    @BindView(R.id.edit_sex)
    TextView editSex;
    private List<String> path = new ArrayList<>();
    private List<String> pathUrl = new ArrayList<>();
    private List<FileInputStream> filelist = new ArrayList<>();
    private String str1 = "", str2 = "";
    private File file1 = null, file2 = null;
    private FileInputStream fileInputStream1, fileInputStream2;
    private boolean lastType = false;


    /**
     * TessBaseAPI初始化用到的第一个参数，是个目录。
     */
    private static final String DATAPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    /**
     * 在DATAPATH中新建这个目录，TessBaseAPI初始化要求必须有这个目录。
     */
    private static final String tessdata = DATAPATH + File.separator + "tessdata";
    /**
     * TessBaseAPI初始化测第二个参数，就是识别库的名字不要后缀名。
     */
    private static String DEFAULT_LANGUAGE = "chi_sim";
    /**
     * assets中的文件名
     */
    private static String DEFAULT_LANGUAGE_NAME = DEFAULT_LANGUAGE + ".traineddata";
    /**
     * 保存到SD卡中的完整文件名
     */
    private static String LANGUAGE_PATH = tessdata + File.separator + DEFAULT_LANGUAGE_NAME;

    /**
     * 权限请求值
     */
    private static final int PERMISSION_REQUEST_CODE = 0;


    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA
    };
    private static final int PERMISSON_REQUESTCODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.name_renzheng);
        ButterKnife.bind(this);
        init();

        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
            }
        }

        assets2SD(getApplicationContext(), LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);

    }

    private void init() {
        title.setText("实名认证");
    }

    @OnClick({R.id.btn_one, R.id.btn_two, R.id.btn_res, R.id.toolber_color_back})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.toolber_color_back:
                finish();
                break;
            case R.id.btn_one:
//                MultiImageSelector.create(this)
//                        .showCamera(true)
//                        .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
//                        .single() // 单选模式
//                        .start(this, 1);

//                intent = new Intent(this, NameRenzhengPhoneActivity.class);
//                startActivityForResult(intent, 111);
                lastType = true;
                this.startCaptureNewActivity(this.idCallBackNew, lastType, false);
                break;
            case R.id.btn_two:
//                MultiImageSelector.create(this)
//                        .showCamera(true)
//                        .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
//                        .single() // 单选模式
//                        .start(this, 2);

//                intent = new Intent(this, NameRenzhengPhoneActivity.class);
//                startActivityForResult(intent, 222);

                lastType = false;
                this.startCaptureNewActivity(this.idCallBackNew, lastType, false);
                break;
            case R.id.btn_res:
                if (str1.equals("")) {
                    Toast.makeText(this, "请重新上传身份证人像面照片！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (str2.equals("")) {
                    Toast.makeText(this, "请重新上传身份证国徽面照片！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (file1 == null || file2 == null) {
                    Toast.makeText(this, "请联系客服！", Toast.LENGTH_SHORT).show();
                    return;
                }
                createLoadingDialog(this, "上传图片中,请稍后...", true);
                volleyLogin();
                break;
        }
    }

    private void startCaptureNewActivity(MLCnIcrCapture.CallBack callBack, boolean isFront, boolean isRemote) {
        MLCnIcrCaptureConfig config =
                new MLCnIcrCaptureConfig.Factory().setFront(isFront).setRemote(isRemote).create();
        MLCnIcrCapture icrCapture = MLCnIcrCaptureFactory.getInstance().getIcrCapture(config);
        icrCapture.capture(callBack, this);
    }

    private MLCnIcrCapture.CallBack idCallBackNew = new MLCnIcrCapture.CallBack() {
        @Override
        public void onSuccess(MLCnIcrCaptureResult idCardResult) {
            if (idCardResult == null)
                return;
            Bitmap bitmap = idCardResult.cardBitmap;
            if (lastType) {
                if (idCardResult.name.equals("") || idCardResult.sex.equals("") || idCardResult.idNum.equals("")) {
                    namell.setVisibility(View.GONE);
                    sexll.setVisibility(View.GONE);
                    sfzhll.setVisibility(View.GONE);
                    cityll.setVisibility(View.GONE);
                    str1 = "";
                    return;
                }
                btnOne.setImageBitmap(bitmap);
                namell.setVisibility(View.VISIBLE);
                sexll.setVisibility(View.VISIBLE);
                sfzhll.setVisibility(View.VISIBLE);
                editName.setText(idCardResult.name);
                editSex.setText(idCardResult.sex);
                editSfzh.setText(idCardResult.idNum);
                str1 = "111111111111111";
                if (!idCardResult.address.equals("")) {
                    eidtCity.setText(idCardResult.address);
                    cityll.setVisibility(View.VISIBLE);
                }
                file1 = getFile(bitmap);
//                try {
//                    file1 = saveFile(compressBitmap(bitmap, 200), getTime());
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            } else {
                Log.e("sss", idCardResult.validDate);
                btnTwo.setImageBitmap(bitmap);
                str2 = "22222222222222222222";
//                try {
//                    file2 = saveFile(compressBitmap(bitmap, 200), getTime());
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                file2 = getFile(bitmap);
            }

        }

        @Override
        public void onCanceled() {
            if (lastType) {
                str1 = "";
                namell.setVisibility(View.GONE);
                sexll.setVisibility(View.GONE);
                sfzhll.setVisibility(View.GONE);
                cityll.setVisibility(View.GONE);
            } else {
                str2 = "";
            }
        }

        @Override
        public void onFailure(int i, Bitmap bitmap) {
            if (lastType) {
                str1 = "";
                namell.setVisibility(View.GONE);
                sexll.setVisibility(View.GONE);
                sfzhll.setVisibility(View.GONE);
                cityll.setVisibility(View.GONE);
            } else {
                str2 = "";
            }
        }

        @Override
        public void onDenied() {
            if (lastType) {
                str1 = "";
                namell.setVisibility(View.GONE);
                sexll.setVisibility(View.GONE);
                sfzhll.setVisibility(View.GONE);
                cityll.setVisibility(View.GONE);
            } else {
                str2 = "";
            }
        }
    };


    /**
     * 上传文件
     *
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @return
     */
    String res = "";

//    public String formUpload(String urlStr, Map<String, String> textMap,
//                             Map<String, String> fileMap) {
//        String BOUNDARY = "---------------------------"; // boundary就是request头和上传文件内容的分隔符
//        try {
//            URL url = new URL(urlStr);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setConnectTimeout(300000);
//            conn.setReadTimeout(300000);
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            conn.setUseCaches(false);
//            conn.setRequestMethod("POST");
//            conn.setRequestProperty("Connection", "Keep-Alive");
//            conn.setRequestProperty("User-Agent",
//                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
//            conn.setRequestProperty("Content-Type",
//                    "multipart/form-data; boundary=" + BOUNDARY);
//
//            OutputStream out = new DataOutputStream(conn.getOutputStream());
//            // text
//            if (textMap != null) {
//                StringBuffer strBuf = new StringBuffer();
//                for (String inputName : textMap.keySet()) {
//                    String inputValue = textMap.get(inputName);
//                    if (inputValue == null) {
//                        continue;
//                    }
//                    strBuf.append("\r\n").append("--").append(BOUNDARY)
//                            .append("\r\n");
//                    strBuf.append("Content-Disposition: form-data; name=\""
//                            + inputName + "\"\r\n\r\n");
//                    strBuf.append(inputValue);
//                }
//                out.write(strBuf.toString().getBytes());
//            }
//
//            // file
//            if (fileMap != null) {
//                for (String inputName : fileMap.keySet()) {
//                    String inputValue = fileMap.get(inputName);
//                    if (inputValue == null) {
//                        continue;
//                    }
//                    File file = new File(inputValue);
//                    String filename = file.getName();
//                    String contentType = null;
//                    // new MimeTypeMap().getContentType(file);
//                    if (filename.endsWith(".png")) {
//                        contentType = "image/png";
//                    }
//                    if (filename.endsWith(".jpeg")) {
//                        contentType = "image/jpeg";
//                    }
//                    if (filename.endsWith(".jpg")) {
//                        contentType = "image/jpg";
//                    }
//                    if (contentType == null || contentType.equals("")) {
//                        contentType = "application/octet-stream";
//                    }
//
//                    StringBuffer strBuf = new StringBuffer();
//                    strBuf.append("\r\n").append("--").append(BOUNDARY)
//                            .append("\r\n");
//                    strBuf.append("Content-Disposition: form-data; name=\""
//                            + inputName + "\"; filename=\"" + filename
//                            + "\"\r\n");
//                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
//
//                    out.write(strBuf.toString().getBytes());
//
//                    DataInputStream in = new DataInputStream(
//                            new FileInputStream(file));
//                    int bytes = 0;
//                    byte[] bufferOut = new byte[1024];
//                    while ((bytes = in.read(bufferOut)) != -1) {
//                        out.write(bufferOut, 0, bytes);
//                    }
//                    in.close();
//                }
//            }
//
//            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
//            out.write(endData);
//            out.flush();
//            out.close();
//
//            // 读取返回数据
//            StringBuffer strBuf = new StringBuffer();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    conn.getInputStream()));
//            String line = null;
//            while ((line = reader.readLine()) != null) {
//                strBuf.append(line).append("\n");
//            }
//            res = strBuf.toString();
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        JSONObject jsonObject = new JSONObject(res);
//                        JSONObject data = jsonObject.getJSONObject("data");
//                        String link = data.getString("link");
//                        Log.i("图片地址", link);
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            });
//
//
//            Log.i("完成图片", res);
////                }
////            });
//            reader.close();
//            reader = null;
//            if (conn != null) {
//                conn.disconnect();
//                conn = null;
//            }
//        } catch (Exception e) {
//            dismisProgressDialog();
//            e.printStackTrace();
//        } finally {
//            dismisProgressDialog();
//
//        }
//        return res;
//    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer) checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean) shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {

            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否所有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class,
                            int.class});
                    method.invoke(this, array, PERMISSON_REQUESTCODE);
                } else {
//                    shangchuanImg();
                }
            } else {
//                shangchuanImg();
            }
        } catch (Throwable e) {

        }
    }


    @Override
    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                // showMissingPermissionDialog();
                checkPermissions(needPermissions);
            } else {
//                shangchuanImg();

            }
        }
    }

    ;


    ///*
//* 实名认证
//* */
    public void volleyLogin() {
        Log.e("实名认证", "实名认证开始");

        JSONObject json_url = new JSONObject();
        try {
            json_url.put("userName", editName.getText().toString());
            json_url.put("userId", BcUtils.getUid());
            json_url.put("userHomeAddress", eidtCity.getText().toString());
            json_url.put("userGender", editSex.getText().toString());
            json_url.put("userIdNum", editSfzh.getText().toString());
            json_url.put("suffix", ".png");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        OkHttpUtils.post()
                .addParams("inputParameter", DataCheck.signCheck(json_url.toString()))
                .addFile("upload", System.currentTimeMillis() + "1.png", file1)
                .addFile("upload", System.currentTimeMillis() + "2.png", file2)
                .url(Constants.SHIMINGRENZHENG)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("sss", "" + e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("实名认证", response);
                        //s为请求返回的字符串数据
                        try {
                            JSONObject json = new JSONObject(response);
                            String code = json.getString("code");
                            String msg = json.getString("msg");
                            if (code.equals("1")) {
                                toast("实名认证成功");
                                BcUtils.getUserInfo().setUserState("1");
                                HomeFragment.userStart = 1;
//                                startAction(MainActivity.class);
                                finish();
                            } else {
                                toast(msg);
                            }
                            dismisProgressDialog();
                        } catch (Exception e) {
                            e.printStackTrace();
                            dismisProgressDialog();
                        }
                    }
                });
//        final Gson mGson = new Gson();
//        String url = Constants.SHIMINGRENZHENG;
//        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                dismisProgressDialog();
//                Log.i("实名认证", s);
//                //s为请求返回的字符串数据
//                try {
//                    JSONObject json = new JSONObject(s);
//                    String code = json.getString("code");
//                    if (code.equals("1")) {
//                        toast("实名认证成功");
//                        BcUtils.getUserInfo().setUserState("1");
//                        startAction(MainActivity.class);
//                    } else {
//                        Log.i("站好", "账号");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    dismisProgressDialog();
//                }
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//                dismisProgressDialog();
//                toast("请求失败");
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数
//
//                HashMap<String, String> map = new HashMap<String, String>();
//                JSONObject json_url = new JSONObject();
//                JSONObject json_url1 = new JSONObject();
//                try {
//                    json_url.put("userName", editName.getText().toString());
//                    json_url.put("userId", BcUtils.getUid());
//                    json_url.put("userHomeAddress", eidtCity.getText().toString());
//                    json_url.put("userGender", editSex.getText().toString());
//                    json_url.put("userIdNum", editSfzh.getText().toString());
//                    json_url1.put("upload", filelist);
//                    json_url.put("suffix", ".png");
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
//                map.put("upload", filelist + "");
//                return map;
//            }
//        };
//        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    //回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 111) {
            byte[] bytes = data.getByteArrayExtra("image");
            if (bytes.length == 0) {
                return;
            }
            recognition(Bytes2Bimap(bytes));
            btnOne.setImageBitmap(Bytes2Bimap(bytes));
        }
        if (requestCode == 222) {
            byte[] bytes = data.getByteArrayExtra("image");
            if (bytes.length == 0) {
                return;
            }
            recognitionTwo(Bytes2Bimap(bytes));
            btnTwo.setImageBitmap(Bytes2Bimap(bytes));
        }
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                // 获取返回的图片列表
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                System.out.println("图片路径" + path);
                // 处理你自己的逻辑 ....
                assert path != null;
                try {
                    FileInputStream fs = new FileInputStream(path.get(0));
                    filelist.add(fs);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Tools.loadImg(path.get(0), btnOne);
            }
        } else if (requestCode == 2) {
            if (resultCode == RESULT_OK) {
                // 获取返回的图片列表
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                System.out.println("图片路径2" + path);
                assert path != null;
                Tools.loadImg(path.get(0), btnTwo);
                try {
                    FileInputStream fs = new FileInputStream(path.get(0));
                    filelist.add(fs);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 处理你自己的逻辑 ....
            }
        }
    }

    private void recognitionTwo(Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String text = "";
                if (!checkTraineddataExists()) {
                    assets2SD(getApplicationContext(), LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
                }
                final String finalText = text;
//                final Bitmap finalBitmap = bitmap;
                final Bitmap finalBitmap = compressBitmap(bitmap, 200);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        startCaptureActivity(idCallback1, false, false, finalBitmap);

                        try {
                            file2 = saveFile(finalBitmap, getTime());
                            fileInputStream2 = new FileInputStream(file2);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    private void recognition(Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String text = "";
                if (!checkTraineddataExists()) {
                    assets2SD(getApplicationContext(), LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
                }
                final String finalText = text;
//                final Bitmap finalBitmap = bitmap;
                final Bitmap finalBitmap = compressBitmap(bitmap, 200);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

//                        startCaptureActivity(idCallback, true, false, finalBitmap);
                        startCaptureActivity(idCallback, true, false, bitmap);

                        try {
                            file1 = saveFile(finalBitmap, getTime());
                            fileInputStream1 = new FileInputStream(file1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    public Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    public static void assets2SD(Context context, String path, String name) {

        //如果存在就删掉
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
        if (!f.exists()) {
            File p = new File(f.getParent());
            if (!p.exists()) {
                p.mkdirs();
            }
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        InputStream is = null;
        OutputStream os = null;
        try {
            is = context.getAssets().open(name);
            File file = new File(path);
            os = new FileOutputStream(file);
            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public boolean checkTraineddataExists() {
        File file = new File(LANGUAGE_PATH);
        return file.exists();
    }

    public static String convertIconToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] appicon = baos.toByteArray();// 转为byte数组
        String img = Base64.encodeToString(appicon, Base64.DEFAULT);
        return img;
    }

    private Bitmap compressBitmap(Bitmap bitmap, long sizeLimit) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        while (baos.toByteArray().length / 1024 > sizeLimit) {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 10;
        }
        Bitmap newBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);
        return newBitmap;
    }

    public File saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/Ask";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;
    }


    public String getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String timeString = formatter.format(curDate);

        String timeStamp = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");
        Date d;
        try {
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeStamp;
    }


    private void startCaptureActivity(MLCnIcrCapture.CallBack callback, boolean isFront, boolean isRemote, Bitmap bitmap) {
        MLCnIcrCaptureConfig config = new MLCnIcrCaptureConfig.Factory()
                .setFront(true)
                .setRemote(false)
                .create();
        MLCnIcrCapture icrCapture = MLCnIcrCaptureFactory.getInstance().getIcrCapture(config);
        icrCapture.captureImage(bitmap, callback);
    }

    private MLCnIcrCapture.CallBack idCallback = new MLCnIcrCapture.CallBack() {
        @Override
        public void onSuccess(MLCnIcrCaptureResult idCardResult) {
            Log.e("sss", "...........识别成功处理");
            if (idCardResult.name.equals("") || idCardResult.sex.equals("") || idCardResult.idNum.equals("")) {
                namell.setVisibility(View.GONE);
                sexll.setVisibility(View.GONE);
                sfzhll.setVisibility(View.GONE);
                cityll.setVisibility(View.GONE);
                str1 = "";
                return;
            }
            namell.setVisibility(View.VISIBLE);
            sexll.setVisibility(View.VISIBLE);
            sfzhll.setVisibility(View.VISIBLE);
            editName.setText(idCardResult.name);
            editSex.setText(idCardResult.sex);
            editSfzh.setText(idCardResult.idNum);
            str1 = "111111111111111";
            if (!idCardResult.address.equals("")) {
                eidtCity.setText(idCardResult.address);
                cityll.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onCanceled() {
            Log.e("sss", "...........用户取消处理");
            str1 = "";
            namell.setVisibility(View.GONE);
            sexll.setVisibility(View.GONE);
            sfzhll.setVisibility(View.GONE);
            cityll.setVisibility(View.GONE);
        }

        @Override
        public void onFailure(int retCode, Bitmap bitmap) {
            Log.e("sss", retCode + "...........识别异常处理");
            str1 = "";
            namell.setVisibility(View.GONE);
            sexll.setVisibility(View.GONE);
            sfzhll.setVisibility(View.GONE);
            cityll.setVisibility(View.GONE);
        }

        @Override
        public void onDenied() {
            Log.e("sss", "...........相机不支持等场景处理");
            str1 = "";
            namell.setVisibility(View.GONE);
            sexll.setVisibility(View.GONE);
            sfzhll.setVisibility(View.GONE);
            cityll.setVisibility(View.GONE);
        }
    };


    private MLCnIcrCapture.CallBack idCallback1 = new MLCnIcrCapture.CallBack() {
        @Override
        public void onSuccess(MLCnIcrCaptureResult idCardResult) {
            Log.e("sss", "...........识别成功处理");
            str2 = "22222222222222222222";
        }

        @Override
        public void onCanceled() {
            Log.e("sss", "...........用户取消处理");
            str2 = "";
        }

        @Override
        public void onFailure(int retCode, Bitmap bitmap) {
            Log.e("sss", retCode + "...........识别异常处理");
            str2 = "";
        }

        @Override
        public void onDenied() {
            Log.e("sss", "...........相机不支持等场景处理");
            str2 = "";
        }
    };


    public File getFile(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        File file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            int x = 0;
            byte[] b = new byte[1024 * 100];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

}
